package com.googlecode.gxtmvp.rest.client;

import com.extjs.gxt.ui.client.data.BaseListLoadResult;
import com.extjs.gxt.ui.client.data.BaseListLoader;
import com.extjs.gxt.ui.client.data.ListLoadResult;
import com.google.gwt.user.client.rpc.AsyncCallback;

import java.util.List;

public class RestListLoader<D, C> extends BaseListLoader<ListLoadResult<D>> {
  
  private final RestService rest;
  private final CollectionResource<D> resource;
  private final Codec<String, C, List<D>> codec;
  private final C modelType;
  
  public RestListLoader(final RestService rest, final CollectionResource<D> resource,
      final Codec<String, C, List<D>> codec, final C modelType) {
    super(null);
    this.rest = rest;
    this.resource = resource;
    this.codec = codec;
    this.modelType = modelType;
  }
  
  @Override
  protected void loadData(final Object loadConfig, final AsyncCallback<ListLoadResult<D>> callback) {
    rest.send(resource.get(codec, modelType), new AsyncCallback<List<D>>() {
      @Override
      public void onFailure(final Throwable caught) {
        callback.onFailure(caught);
      }
      
      @Override
      public void onSuccess(final List<D> result) {
        callback.onSuccess(new BaseListLoadResult<D>(result));
      }
    });
  }
  
}
